package com.wmada.toolkit.common.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author will.ma
 * @date 2018-6-8
 */
public class BufferedConsumer<T> implements Consumer<T> {

    private static final Logger LOGGER = LoggerFactory.getLogger(BufferedConsumer.class);

    private final Integer           batchSize;
    private final Consumer<List<T>> consumer;

    private final List<T> buffer;

    public BufferedConsumer(Integer batchSize, Consumer<List<T>> consumer) {
        this.batchSize = batchSize;
        this.consumer = consumer;

        this.buffer = new ArrayList<>(batchSize);
    }

    synchronized public BufferedConsumer<T> add(T data) {
        if (buffer.size() == batchSize) {
            flush();
        }
        buffer.add(data);
        return this;
    }

    public BufferedConsumer<T> flush() {
        LOGGER.trace("Flush {} data to consumer.", buffer.size());
        consumer.accept(buffer);
        buffer.clear();
        return this;
    }

    public BufferedConsumer<T> done() {
        if (buffer.size() > 0) {
            flush();
        }
        return this;
    }

    @Override
    public void accept(T t) {
        add(t);
    }
}
